<template>
    <div style=" position: relative;">
        <el-card class="card_css">
            <template #header>
                <!-- 头部信息 -->
                <div class="dgts-row">
                    <div class="dgts-text-tj1">
                        <b class="tr-it-title c-green">累计</b>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">收入{{ totalGath }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">支出：{{ totalPay }} 元</span>
                    </div>

                    <div class="dgts-text-tj2">
                        <b class="tr-it-title c-green">所选</b>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">收入{{ seledGath }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">支出：{{ seledPay }} 元</span>
                    </div>
                </div>
                <!-- 搜索 -->
                <div style="margin-top:10px;">
                    <el-select size="small" v-model="find_data.timeType" placeholder="时间类型" style="width: 90px;">
                        <el-option label="添加时间" value="1"></el-option>
                        <el-option label="发生时间" value="2"></el-option>
                    </el-select>

                    <el-date-picker :default-time="defaultTime" size="small" style="margin-left: 10px;width: 290px;"
                        v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                    <el-select size="small" style="margin-left: 10px;width: 160px;" v-model="find_data.reimStatus"
                        clearable multiple collapse-tags placeholder="报账状态">
                        <el-option label="未审核" value="NO_CHECK"></el-option>
                        <el-option label="已审核" value="CHECKED"></el-option>
                        <el-option label="已报销" value="CANCELLATION"></el-option>
                        <el-option label="已拒绝" value="REFUSED"></el-option>
                    </el-select>

                    <el-cascader size="small" style="margin-left: 10px;width: 150px;" v-model="curval2"
                        :options="findAllDeptList_list" :collapse-tags="true" :clearable="true"
                        :props="{ multiple: true, checkStrictly: true, emitPath: true, value: 'id', label: 'deptName' }"
                        placeholder="请选择部门" :show-all-levels="false" @change="handleChange_find">
                        <template #="{ node, data }">
                            <span>{{ data.deptName }}</span>
                            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                        </template>
                    </el-cascader>

                    <el-select size="small" style="margin-left: 10px;width: 100px;" v-model="find_data.operUserId"
                        clearable filterable placeholder="经办人">
                        <el-option v-for="item in serviceManList" :key="item.ftUserId" :label="item.realName"
                            :value="item.ftUserId">
                        </el-option>
                    </el-select>

                    <el-input size="small" style="margin-left: 10px;width: 100px;" v-model="find_data.reimUser"
                        placeholder="收款人" clearable />

                    <el-input type="number" size="small" style="margin-left: 10px;width: 100px;"
                        v-model="find_data.reimMoney" placeholder="报账金额" clearable />

                    <el-select size="small" style="margin-left: 10px;width: 160px;" v-model="find_data.tradeStatus"
                        clearable placeholder="收支类型">
                        <el-option label="收入" value="0"></el-option>
                        <el-option label="支出" value="1"></el-option>
                    </el-select>

                </div>

                <div>
                    <el-select size="small" v-model="find_data.plateNum" clearable filterable placeholder="车牌号"
                        style="width: 100px">
                        <el-option v-for="item in carNumList" :key="item.id" :label="item.plate_num"
                            :value="item.plate_num">
                        </el-option>
                    </el-select>
                    <el-select size="small" style="margin-left: 10px;width:140px" multiple
                        v-model="find_data.moneyTypeIds" clearable collapse-tags filterable placeholder="金额类型">
                        <el-option v-for="item in reimTypeOptions" :key="item.id" :label="item.val" :value="item.id">
                        </el-option>
                    </el-select>

                    <el-input size="small" style="margin-left: 10px;width: 150px;" v-model="find_data.operMark"
                        placeholder="操作标示" clearable />

                    <el-input size="small" style="margin-left: 10px;width: 150px;" v-model="find_data.omsOrderNum"
                        placeholder="行程订单号" clearable />

                    <el-input size="small" style="margin-left: 10px;width: 150px;" v-model="find_data.remark"
                        placeholder="摘要/其他费用说明" clearable />



                    <el-button size="small" style="margin-left: 20px;margin-top: 2px;" @click="search_btn"
                        type="primary" icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button size="small" @click="add_btn" type="primary" icon="SuccessFilled">新增</el-button>
                    <el-button size="small" @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button size="small" @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                    <el-button size="small" @click="checkBzRecord('CHECKED')" type="primary"
                        icon="Stamp">审核通过</el-button>
                    <el-button size="small" @click="checkBzRecord('REFUSED')" type="primary"
                        icon="Stamp">审核不通过</el-button>
                    <el-button size="small" @click="setTurnDownStaffReimMd" type="primary"
                        icon="DocumentRemove">驳回</el-button>
                    <el-button size="small" @click="Write_off_btn" type="primary" icon="DocumentCopy">核销</el-button>
                    <el-button size="small" @click="cancelWriteOff" type="primary" icon="Close">撤销核销</el-button>
                    <el-button size="small" @click="ex_getWalletListForBack_btn" type="primary"
                        icon="Download">导出</el-button>
                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="54vh"
                    ref="multipleTableRef" :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'reimVoucherUrl'" #="{ row, column, $index }">
                                <template v-if="row.reimVoucherUrl">
                                    <el-image v-for="item in row.reimVoucherUrl.split(',')"
                                        style="width: 40px; height: 40px" :preview-teleported="true"
                                        :preview-src-list="[ImageUrl + item]" :src="item ? ImageUrl + item : ''"
                                        fit="cover">
                                        <template #error>
                                            <div>
                                                <el-icon style="width: 95px; height: 95px"><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </template>


                            </template>
                            <template v-if="item.field == 'operNote'" #="{ row, column, $index }">

                                <el-tooltip :popper-class="'route-tips'" placement="left">
                                    <template #content>{{ row.operNote }}</template>
                                    <span style="  width: 100px; white-space: nowrap; text-overflow: ellipsis; ">{{
                                        row.operNote }}</span>
                                </el-tooltip>

                            </template>
                            <template v-if="item.field == 'isCheck'" #="{ row, column, $index }">
                                <b v-if="row.isCheck == 'NO_CHECK'" style="color: #FF7300">未审核</b>
                                <b v-else-if="row.isCheck == 'CHECKED'" style="color: #008000">已审核</b>
                                <b v-else-if="row.isCheck == 'CANCELLATION'">已报销</b>
                                <b v-else style="color: red;">未通过</b>
                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:200px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="45%" :close-on-click-modal='false'>
            <!-- <el-button v-if="add_up_off == 1" style="margin-bottom: 10px" type="primary" icon="Plus" @click="handleAdd">
                添加
            </el-button> -->
            <el-form :model="add_data" ref="formRef" label-width="100px" size="medium">
                <el-form-item label="经办人:" prop="tableData[0].operUseId"
                    :rules="[{ required: true, message: '请选择金额类型', trigger: 'change' }]">
                    <el-select style="width:300px" v-model="add_data.tableData[0].operUseId" clearable filterable
                        placeholder="经办人">
                        <el-option v-for="item in serviceManList" :key="item.ftUserId" :label="item.realName"
                            :value="item.ftUserId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="报账人:" prop="tableData[0].reimUser"
                    :rules="[{ required: false, message: '请选择报账人', trigger: 'change' }]">

                    <el-select clearable style="width: 300px;" filterable remote
                        :filter-method="cusOptions_handleFilter" v-model="add_data.tableData[0].reimUserId"
                        placeholder="请选择报账人">
                        <el-option v-for="(item, index) in getStaffReimUser_list" :key="index" :label="item.val"
                            :value="item.id">

                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="车牌号:" prop="tableData[0].plateNum"
                    :rules="[{ required: false, message: '请选择车牌号', trigger: 'change' }]">

                    <el-select v-model="add_data.tableData[0].plateNum" clearable filterable placeholder="车牌号"
                        style="width:300px">
                        <el-option v-for="item in carNumList" :key="item.id" :label="item.plate_num"
                            :value="item.plate_num">
                        </el-option>
                    </el-select>

                </el-form-item>
                <el-form-item label="金额类型:" prop="tableData[0].moneyTypeId"
                    :rules="[{ required: true, message: '请选择金额类型', trigger: 'change' }]">
                    <el-select @change="reimTypeOptions_change" style="width:300px"
                        v-model="add_data.tableData[0].moneyTypeId" clearable filterable placeholder="金额类型">
                        <el-option v-for="item in reimTypeOptions" :key="item.id" :label="item.val" :value="item.id">
                        </el-option>
                    </el-select>
                    <span style="color:red;margin-left: 10px;">{{ add_data.tableData[0].moneyTypeId ?
                        '【' + reimTypeOptions_com(add_data.tableData[0].moneyTypeId) + '】' : '' }}</span>
                </el-form-item>
                <el-form-item v-if='reimTypeOptionsname == "收入" || reimTypeOptionsname == "互转"' label="收入金额:"
                    prop="tableData[0].gathMoney" :rules="[
                        { required: false, message: '请输入收入金额', trigger: 'blur' },

                    ]">
                    <el-input placeholder="收入金额" style="width:300px" type="number"
                        v-model="add_data.tableData[0].gathMoney"></el-input>

                </el-form-item>
                <el-form-item v-if='reimTypeOptionsname == "支出" || reimTypeOptionsname == "互转"' label="支出金额:"
                    prop="tableData[0].reimMoney" :rules="[
                        { required: false, message: '请输入支出金额', trigger: 'blur' },

                    ]">
                    <el-input placeholder="支出金额" style="width:300px" type="number"
                        v-model="add_data.tableData[0].reimMoney"></el-input>

                </el-form-item>
                <el-form-item label="报账图片:" prop="tableData[0].reimVoucherUrl"
                    :rules="[{ required: false, message: '请上传报账图片', trigger: 'change' }]">

                    <!-- <el-upload class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                        @click="picture_click(scope)" :data="{ ftype: 'BACK_SET_DATA_IMG', files: rawFile_list }"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :show-file-list="false">
                        <img v-if="add_data.tableData[0].reimVoucherUrl"
                            :src="ImageUrl + add_data.tableData[0].reimVoucherUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload> -->

                    <el-upload :limit="6" v-model:file-list="adupRewardPunish_rawFile_list2" style="margin-top: 10px;"
                        class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                        :data="{ ftype: 'BACK_SET_DATA_IMG', files: rawFile_list }" list-type="picture-card"
                        :on-remove="handleRemove1" :on-preview="handlePictureCardPreview1"
                        :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload1">

                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible1">
                        <div style="width:60vh;height:60vh;margin:auto;">
                            <img style="width:60vh;height:60vh;margin:auto;" :src="ImageUrl + dialogImageUrl1"
                                alt="Preview Image" />
                        </div>
                    </el-dialog>
                </el-form-item>
                <el-form-item v-if='expireTimeoff == "212"' label="下次到期时间:" prop="tableData[0].expireTime"
                    :rules="[{ required: true, message: '下次到期时间', trigger: 'blur' }]">

                    <el-date-picker clearable style="width: 300px" v-model="add_data.tableData[0].expireTime"
                        type="date" placeholder="下次到期时间" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label-width="120px" v-if='expireTimeoff == "212"' label="提前提醒天数:"
                    prop="tableData[0].remindDays" :rules="[{ required: true, message: '提前提醒天数', trigger: 'blur' }]">
                    <el-input placeholder="提前提醒天数" style="width:300px" v-model="add_data.tableData[0].remindDays">
                    </el-input>
                </el-form-item>
                <el-form-item label="摘要:" prop="tableData[0].remark"
                    :rules="[{ required: true, message: '摘要', trigger: 'blur' }]">
                    <el-input placeholder="摘要" style="width:500px" type="textarea"
                        v-model="add_data.tableData[0].remark">
                    </el-input>
                </el-form-item>
                <!-- <el-table ref="tableRef" :data="add_data.tableData" border fit
                    :height="add_up_off == 1 ? '115' : '115'">
                    <el-table-column label="经办人">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.operUseId'"
                                :rules="[{ required: true, message: '请选择金额类型', trigger: 'change' }]">
                                <el-select style="margin-top: 10px;width:120px" v-model="scope.row.operUseId" clearable
                                    filterable placeholder="经办人">
                                    <el-option v-for="item in serviceManList" :key="item.ftUserId"
                                        :label="item.realName" :value="item.ftUserId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="报账人">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.reimUser'"
                                :rules="[{ required: false, message: '请选择报账人', trigger: 'change' }]">
                               
                                <el-select clearable style="width: 200px;" filterable remote
                                    :filter-method="cusOptions_handleFilter" v-model="scope.row.reimUserId"
                                    placeholder="请选择报账人">
                                    <el-option v-for="(item, index) in getStaffReimUser_list" :key="index"
                                        :label="item.val" :value="item.id">

                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="车牌号">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.plateNum'"
                                :rules="[{ required: false, message: '请选择车牌号', trigger: 'change' }]">

                                <el-select v-model="scope.row.plateNum" clearable filterable placeholder="车牌号"
                                    style="margin-top: 10px;width:120px">
                                    <el-option v-for="item in carNumList" :key="item.id" :label="item.plate_num"
                                        :value="item.plate_num">
                                    </el-option>
                                </el-select>

                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column width="220" label="金额类型">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.moneyTypeId'"
                                :rules="[{ required: true, message: '请选择金额类型', trigger: 'change' }]">
                                <el-select @change="reimTypeOptions_change" style="margin-top: 10px;width:120px" v-model="scope.row.moneyTypeId"
                                    clearable filterable placeholder="金额类型">
                                    <el-option v-for="item in reimTypeOptions" :key="item.id" :label="item.val"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                                <span style="color:red;margin-left: 10px;">{{ scope.row.moneyTypeId ?
                                    '【' + reimTypeOptions_com(scope.row.moneyTypeId) + '】' : '' }}</span>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="收入金额" v-if='reimTypeOptionsname != "支出"'>
                        <template #default="scope">
                            <el-form-item v-if='reimTypeOptionsname != "支出"' :prop="'tableData.' + scope.$index + '.gathMoney'" :rules="[
                                { required: false, message: '请输入收入金额', trigger: 'blur' },

                            ]">
                                <el-input placeholder="收入金额" style="margin-top: 10px;width:120px" type="number"
                                    v-model="scope.row.gathMoney"></el-input>

                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="支出金额" v-if='reimTypeOptionsname != "收入"'>
                        <template #default="scope">
                            <el-form-item v-if='reimTypeOptionsname != "收入"' :prop="'tableData.' + scope.$index + '.reimMoney'" :rules="[
                                { required: false, message: '请输入支出金额', trigger: 'blur' },

                            ]">
                                <el-input placeholder="支出金额" style="margin-top: 10px;width:120px" type="number"
                                    v-model="scope.row.reimMoney"></el-input>

                            </el-form-item>
                        </template>
                    </el-table-column>


                    <el-table-column label="图片">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.reimVoucherUrl'"
                                :rules="[{ required: false, message: '请上传报账图片', trigger: 'change' }]">

                                <el-upload style="margin-top: 10px;" class="avatar-uploader" :action="ImageUrl_upload"
                                    :headers="{ token: GET_TOKEN() }" @click="picture_click(scope)"
                                    :data="{ ftype: 'BACK_SET_DATA_IMG', files: rawFile_list }"
                                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                    :show-file-list="false">
                                    <img v-if="scope.row.reimVoucherUrl" :src="ImageUrl + scope.row.reimVoucherUrl"
                                        class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                        </template>
                    </el-table-column>
                  
                    <el-table-column v-if='expireTimeoff == "212"' width="120" label="下次到期时间">
                        <template #default="scope">
                            <el-form-item   v-if='expireTimeoff == "212"' :prop="'tableData.' + scope.$index + '.expireTime'"
                                :rules="[{ required: true, message: '下次到期时间', trigger: 'blur' }]">
                             
                                <el-date-picker clearable style="width: 100%" v-model="scope.row.expireTime"
                                type="date" placeholder="下次到期时间" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column v-if='expireTimeoff == "212"' width="120" label="提前提醒天数">
                        <template #default="scope">
                            <el-form-item  v-if='expireTimeoff == "212"' :prop="'tableData.' + scope.$index + '.remindDays'"
                                :rules="[{ required: true, message: '提前提醒天数', trigger: 'blur' }]">
                                <el-input placeholder="提前提醒天数" style="margin-top: 10px;width:200px"
                                    v-model="scope.row.remindDays">
                                </el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column width="200" label="摘要">
                        <template #default="scope">
                            <el-form-item :prop="'tableData.' + scope.$index + '.remark'"
                                :rules="[{ required: true, message: '摘要', trigger: 'blur' }]">
                                <el-input placeholder="摘要" style="margin-top: 10px;width:200px"
                                    v-model="scope.row.remark">
                                </el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="add_up_off == 1" width="110" label="操作">
                        <template #default="scope">
                            <el-button icon="Delete" type="danger" @click="handleDelete(scope)">
                                删 除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table> -->
            </el-form>


            <el-button @click="ok_btn()" style="margin-left:35vw" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 驳回 -->
        <el-dialog style="margin-top:5vh" v-model="setTurnDownStaffReimMd_off" title="报账驳回" width="40%"
            :close-on-click-modal='false'>
            <el-form :model="setTurnDownStaffReimMd_data" ref="setTurnDownStaffReimMd_ref" label-width="100px">
                <el-form-item label="拒绝原因" prop="refuseReason"
                    :rules="[{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]">
                    <el-input v-model="setTurnDownStaffReimMd_data.refuseReason" type="textarea" :rows="4"
                        resize="none" />
                </el-form-item>
            </el-form>
            <el-button @click="setTurnDownStaffReimMd_ok_btn()" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 核销 -->
        <el-dialog style="margin-top:5vh" v-model="Write_off" title="报账核销" width="80%" :close-on-click-modal='false'>
            <div class="filter-container">
                <div class="dgts-row">
                    <el-form :model="Write_data" ref="cancelStaffReimTb" :inline="true" style="margin-right: 20px;">
                        <el-form-item label="入账月份">
                            <el-date-picker v-model="Write_data.enterTime" type="month" placeholder="入账月份"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 120px;" />
                        </el-form-item>

                        <el-button type="primary" icon="SuccessFilled" @click="Write_ok_btn">
                            确定核销
                        </el-button>
                    </el-form>

                    <div class="dgts-text-tj1">
                        <b class="tr-it c-green">累计</b>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-green">收入：{{ Write_totalshou }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">支出：{{ Write_totalPay }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-yellow">收支差额：{{ Write_totalcha }} 元</span>
                    </div>

                    <div class="dgts-text-tj2">
                        <b class="tr-it c-green">所选</b>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-green">收入：{{ Write_seledGath }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-red">支出：{{ Write_seledPay }} 元</span>
                        <el-divider direction="vertical"></el-divider>
                        <span class="tr-it c-yellow">收支差额：{{ Write_seledBalance }} 元</span>
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="dgts-row">
                    <el-form :model="Write_data__find_list" :inline="true">
                        <el-form-item>
                            <el-select v-model="Write_data__find_list.timeType" placeholder="时间类型"
                                style="width: 100px;">
                                <el-option label="添加时间" value="0"></el-option>
                                <el-option label="发生时间" value="1"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item>

                            <el-date-picker style="width: 330px;height:30px" v-model="Write_timeTypeTime"
                                @change="Write_timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                                end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>

                        <el-form-item>
                            <el-input placeholder="交易金额" clearable maxlength="6"
                                v-model="Write_data__find_list.tradeMoney" style="width: 100px;" />
                        </el-form-item>

                        <el-form-item>

                            <el-select style="width: 130px;" v-model="Write_data__find_list.moneyTypeIds" clearable
                                filterable placeholder="金额类型">
                                <el-option v-for="item in reimTypeOptions" :key="item.id" :label="item.val"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>

                            <el-select clearable v-model="Write_data__find_list.tradeStatus" placeholder="收支类型"
                                style="width: 100px;">
                                <el-option label="收入" value="0"></el-option>
                                <el-option label="支出" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-input placeholder="对方户名" clearable v-model="Write_data__find_list.transName"
                                style="width: 120px;" />
                        </el-form-item>

                        <el-form-item style="width: 200px;">
                            <el-input placeholder="摘要" clearable v-model="Write_data__find_list.remark" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="Write_find_btn">
                                搜索
                            </el-button>
                        </el-form-item>

                    </el-form>
                </div>
            </div>
            <div>
                <el-table border @selection-change="selection_change_btn2" height="58vh" ref="multipleTableRef2"
                    :data="Write_data__list" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <el-table-column prop="tradeTime" label="交易时间" width="165" />
                    <el-table-column prop="moneyTypeName" label="金额类型" width="120" />
                    <el-table-column prop="myBankName" label="银行名称" width="140" />
                    <el-table-column label="报销状态" width="100">
                        <template #="{ row, column, $index }">
                            {{ row.isCheck == 'NO_CHECK' ? '未操作' : row.isCheck == 'CANCELLATION' ? '已报销' : row.isCheck
                                ==
                                'SETTLED' ? '已结算' : '无' }}
                        </template>

                    </el-table-column>

                    <el-table-column prop="transName" label="对方户名" width="110" />
                    <el-table-column prop="tradeInMoney" label="借" width="80" />
                    <el-table-column prop="tradeOutMoney" label="贷" width="80" />
                    <el-table-column prop="balance" label="余额" width="90" />
                    <el-table-column prop="remark" label="摘要" width="" />

                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="Write_current_change_btn" @size-change="Write_size_change_btn"
                    v-model:current-page="Write_data__find_list.page.pageNum"
                    v-model:page-size="Write_data__find_list.page.pageSize" :page-sizes="[20, 50, 100, 200]"
                    :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="Write_data__find_list_total" />
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, findStaffReimList, addStaffReimburse, findStaffCombo, findComboCusList,
    getOfficeMoneyTypes, modifyStaffReimburse, checkStaffReimburse, checkRefuse, findBankTradeList, cancellationStaffReim,
    cancelStaffReim, delStaffReim, findAllDeptList, findCarCombo, adupCompanyVehicle, staffReimExport, getStaffReimUser, findTrusteeshipMeCombo

} from '@/api/financial_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData, ImageUrl_upload, ImageUrl, line2treeData } from '@/utils/common.js'
import * as XLSX from 'xlsx';
import CircularJSON from 'circular-json'
onMounted(async () => {
    // let employee_reimbursement = JSON.parse(localStorage.getItem('employee_reimbursement'))
    // if (employee_reimbursement) {
    //     find_data.find = employee_reimbursement.find
    // }

    getPrivateSetList({
        find: '员工报账',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })

    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })

    findStaffCombo({ staffStates: 'NORMAL,TRY' }).then(res => {
        serviceManList.value = res.data || [];
    })

    getOfficeMoneyTypes({}).then(res => {
        reimTypeOptions.value = res.data || [];
    })
    findAllDeptList({}).then(res => {
        findAllDeptList_list.value = res.data
        findAllDeptList_list.value = line2treeData(findAllDeptList_list.value, 'pid')
        findAllDeptList_list.value = findAllDeptList_list.value[0].children
    })

    findTrusteeshipMeCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        companyName: '',
    }).then(res => {
        let luser = JSON.parse(localStorage.getItem("luser"))
        let luser_companyNum = luser.companyNum
        let companyNums = [luser_companyNum]
        if (res.data) {
            for (let i = 0; i < res.data.length; i++) {
                console.log(res.data[i].companyNum)
                companyNums.push(res.data[i].companyNum)
            }
        }
        findCarCombo({
            page: {
                pageNum: 1,
                pageSize: 999,
            },
            plateNum: '',
            companyNums: companyNums,
        }).then(res => {

            carNumList.value = res.data.list || [];
        })
    })



    getStaffReimUser({}).then(res => {
        getStaffReimUser_list.value = res.data
        getStaffReimUser_list2.value = res.data
    })



    await list_api()

})

const getStaffReimUser_list = ref([])
const getStaffReimUser_list2 = ref([])
const cusOptions_handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = getStaffReimUser_list2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            getStaffReimUser_list.value = results
        } else {
            getStaffReimUser_list.value = []
        }
    } else {
        getStaffReimUser_list.value = getStaffReimUser_list2.value
    }
}
const cusCompany_change = (e, x, y) => {
    console.log(e, x, y)

}
//#region 表格数据处理

const table_data_list = reactive([
    { label: '经办人信息', field: 'operName', width: 100, off: true },
    { label: '收款人信息', field: 'reimUser', width: 160, off: true },
    // { label: '收款人单位名称', field: 'cusCompanyName', width: '100', off: true },
    { label: '车公司信息', field: 'carOrderReim', width: 100, off: true },
    { label: '车牌号', field: 'plateNum', width: 100, off: true },
    { label: '业务部门', field: 'deptName', width: 100, off: true },
    { label: '报账详情', field: 'remark', width: 220, off: true },
    { label: '凭证图片', field: 'reimVoucherUrl', width: 100, off: true },
    { label: '支出金额', field: 'reimMoney', width: 100, off: true },
    { label: '收入金额', field: 'gathMoney', width: 100, off: true },
    { label: '支出金额详情', field: 'reimMoneyDetail', width: 120, off: true },
    { label: '记账审核状态', field: 'isCheck', width: 110, off: true },
    { label: '驳回原因', field: 'refuseReason', width: 220, off: true },
    { label: '报账类型', field: 'moneyTypeName', width: 110, off: true },
    { label: '支付日期', field: 'payTime', width: 170, off: true },
    { label: '费用产生日期', field: 'costStartTime', width: 170, off: true },
    { label: '费用结束日期', field: 'costEndTime', width: 170, off: true },
    { label: '入账月份', field: 'enterTime', width: 170, off: true },
    { label: '下次到期时间', field: 'expireTime', width: 170, off: true },
    { label: '提前提醒天数', field: 'remindDays', width: 170, off: true },
    { label: '添加时间', field: 'addTime', width: 170, off: true },
    { label: '操作标识', field: 'operMark', width: 100, off: true },
    { label: '操作备注', field: 'operNote', width: 220, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '员工报账',
        tbNum: "employee_reimbursement",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

//#region 分页列表
const carNumList = ref([])

const totalGath = ref(0)
const totalPay = ref(0)
const seledPay = computed(() => {
    let money = 0
    let rows = table_list.value
    rows.forEach(it => { money += parseFloat(it.reimMoney); });
    return (money).toFixed(2);

})
const seledGath = computed(() => {
    let money = 0
    let rows = table_list.value
    rows.forEach(it => { money += parseFloat(it.gathMoney); });
    return (money).toFixed(2);

})
const findAllDeptList_list = ref([])
const handleChange_find = (valarr) => {
    console.log(valarr, 'valarr')
    let data = []
    for (let i = 0; i < valarr.length; i++) {

        data.push(valarr[i][valarr[i].length - 1])
    }
    find_data.deptIds = data.join(',')

}

const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    deptIds: '',
    stime: '',
    etime: '',
    moneyTypeIds: [],
    operMark: '',
    operUserId: '',
    omsOrderNum: '',
    plateNum: '',
    reimMoney: '',
    reimStatus: ['NO_CHECK', 'CHECKED'],
    reimUser: '',
    tradeStatus: '1',
    staffReimWay: 0,
    timeType: '1',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}
const expireTimeoff = ref('')
const reimTypeOptions_change = (e) => {
    expireTimeoff.value = e
}
const list_api = () => {

    findStaffReimList(find_data).then(res => {
        list_data.value = res.data.list.list
        total.value = res.data.list.total

        // 累计收入
        totalGath.value = res.data.totalGath ? parseFloat(res.data.totalGath) : 0
        // 累计支出
        totalPay.value = res.data.totalPay ? parseFloat(res.data.totalPay) : 0
    })
}
//#endregion

//#region 添加
// 员工下拉
const serviceManList = ref([])
// 收款人
const filter_loading = ref(false)
const cusUnameOptions = ref([])
const remoteMethod = (query) => {
    if (!query) {
        filter_loading.value = false
        cusUnameOptions.value = []

        return
    }
    filter_loading.value = true
    findComboCusList({
        find: query,
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.code == 1) {
            cusUnameOptions.value = res.data
        }
        filter_loading.value = false
    })

}
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]

// 金额类型
const reimTypeOptions = ref([])
const reimTypeOptionsname = ref('')
const reimTypeOptions_com = (e) => {
    let data = ''
    for (let i = 0; i < reimTypeOptions.value.length; i++) {
        if (reimTypeOptions.value[i].id == e) {
            let obj = reimTypeOptions.value[i].other

            if (obj == 'INCOME') {
                data = '收入'
            } else if (obj == 'OUTPAY') {
                data = '支出'
            } else if (obj == 'TRANS') {
                data = '互转'
            }
        }
    }
    reimTypeOptionsname.value = data
    return data
}
// 图片
const rawFile_list = ref([])
const picture_index = ref('')
const picture_click = ({ $index }) => {

    picture_index.value = $index
}
const handleAvatarSuccess = (response, uploadFile) => {

    if (picture_index.value) {
        picture_index.value = picture_index.value
    } else {
        picture_index.value = 0
    }
    add_data.tableData[picture_index.value].reimVoucherUrl = response.data.file.url
    picture_index.value = ''
}
const adupRewardPunish_rawFile_list = ref([])
const adupRewardPunish_rawFile_list2 = ref([])

const handleRemove1 = (uploadFile, uploadFiles) => {
    console.log(uploadFile, adupRewardPunish_rawFile_list.value)
    let url_data = uploadFile.url
    const path = url_data.replace(/^https:\/\/cba360.com/, '');
    for (let i = 0; i < adupRewardPunish_rawFile_list.value.length; i++) {
        if (adupRewardPunish_rawFile_list.value[i] == path) {
            adupRewardPunish_rawFile_list.value.splice(i, 1);
        }
    }
}
const beforeAvatarUpload1 = (rawFile) => {
    rawFile_list.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list.value.push(rawFile)
    return true

}
const dialogImageUrl1 = ref('')
const dialogVisible1 = ref(false)
const handlePictureCardPreview1 = (uploadFile) => {

    if (uploadFile.response) {
        dialogImageUrl1.value = uploadFile.response.data.file.url
    } else {


        dialogImageUrl1.value = uploadFile.url.split('https://cba360.com')[1]
    }

    dialogVisible1.value = true
}
const handleAvatarSuccess1 = (response, uploadFile) => {

    adupRewardPunish_rawFile_list.value.push(response.data.file.url)
    console.log(adupRewardPunish_rawFile_list.value)

}
const beforeAvatarUpload = (rawFile) => {
    rawFile_list.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list.value.push(rawFile)
    return true

}
// const handlePictureCardPreview = (uploadFile) => {
//     dialogImageUrl.value = uploadFile.url!
//   dialogVisible.value = true
// }



// 添加
const handleAdd = () => {
    add_data.tableData.push({
        operUseId: '',
        reimUser: '',
        reimUserId: '',
        plateNum: '',
        gathMoney: '0',
        reimMoney: '0',
        remark: '',
        reimVoucherUrl: '',
        moneyTypeId: '',
    })
}
// 删除
const handleDelete = ({ $index }) => {
    add_data.tableData.splice($index, 1)
}

const add_off = ref(false)
const title = ref('新增办公室报账')
const add_data = reactive({
    tableData: [
        {
            operUseId: '',
            reimUser: '',
            reimUserId: '',
            plateNum: '',
            gathMoney: '0',
            reimMoney: '0',
            remark: '',
            reimVoucherUrl: '',
            moneyTypeId: '',
        }
    ]
})
const add_up_off = ref('1')
const add_btn = () => {
    title.value = '新增办公室报账'
    add_up_off.value = 1
    add_data.tableData = [
        {
            operUseId: '',
            reimUser: '',
            reimUserId: '',
            plateNum: '',
            gathMoney: '0',
            reimMoney: '0',
            remark: '',
            reimVoucherUrl: '',
            moneyTypeId: '',
            expireTime: '',
            remindDays: '',
        }
    ]
    adupRewardPunish_rawFile_list2.value = []
    adupRewardPunish_rawFile_list.value = []


    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    add_up_off.value = 2
    title.value = '修改办公室报账'
    add_data.tableData[0].operUseId = table_list.value[0].operUserId
    add_data.tableData[0].reimUser = table_list.value[0].reimUser
    add_data.tableData[0].reimUserId = table_list.value[0].reimUserId
    add_data.tableData[0].plateNum = table_list.value[0].plateNum
    add_data.tableData[0].gathMoney = table_list.value[0].gathMoney
    add_data.tableData[0].reimMoney = table_list.value[0].reimMoney
    add_data.tableData[0].remark = table_list.value[0].remark
    add_data.tableData[0].reimVoucherUrl = table_list.value[0].reimVoucherUrl
    add_data.tableData[0].moneyTypeId = String(table_list.value[0].moneyTypeId)
    add_data.tableData[0].expireTime = table_list.value[0].expireTime
    add_data.tableData[0].remindDays = table_list.value[0].remindDays
    expireTimeoff.value = String(table_list.value[0].moneyTypeId)
    adupRewardPunish_rawFile_list2.value = []
    adupRewardPunish_rawFile_list.value = []
    adupRewardPunish_rawFile_list.value = table_list.value[0].reimVoucherUrl ? table_list.value[0].reimVoucherUrl.split(',') : []
    if (adupRewardPunish_rawFile_list.value.length > 0) {
        for (let i = 0; i < adupRewardPunish_rawFile_list.value.length; i++) {
            let data = {
                name: i,
                url: ImageUrl + adupRewardPunish_rawFile_list.value[i]
            }
            adupRewardPunish_rawFile_list2.value.push(data)
        }
    } else {
        adupRewardPunish_rawFile_list2.value = []
    }
    add_off.value = true
}
//#endregion

// 提交
const formRef = ref('')
const ok_btn = () => {

    formRef.value.validate((valid, fields) => {
        if (valid) {
            if (title.value == '新增办公室报账') {
                let list = add_data.tableData;
                list[0].reimVoucherUrl = adupRewardPunish_rawFile_list.value.join(',')

                for (let i = 0; i < list.length; i++) {
                    if (list[i].gathMoney != '0' && list[i].reimMoney != '0') {

                        return ElMessage({
                            message: '收入和支付不能同时存在值',
                            type: 'warning',
                        })
                    }
                    for (let j = 0; j < getStaffReimUser_list2.value.length; j++) {
                        if (list[i].reimUserId == getStaffReimUser_list2.value[j].id) {
                            if (getStaffReimUser_list2.value[j].other) {
                                list[i].reimUser = getStaffReimUser_list2.value[j].other + '-' + getStaffReimUser_list2.value[j].val + '-' + getStaffReimUser_list2.value[j].text
                            } else {
                                list[i].reimUser = getStaffReimUser_list2.value[j].val + '-' + getStaffReimUser_list2.value[j].text
                            }

                        }
                    }
                }
                let ps = {
                    staffReimInfo: list
                }
                addStaffReimburse(ps).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            } else {
                let ps = {
                    id: table_list.value[0].id,
                    moneyTypeId: add_data.tableData[0].moneyTypeId,
                    operUserId: add_data.tableData[0].operUseId,
                    plateNum: add_data.tableData[0].plateNum,
                    gathMoney: add_data.tableData[0].gathMoney,
                    reimMoney: add_data.tableData[0].reimMoney,
                    reimUser: add_data.tableData[0].reimUser,
                    reimUserId: add_data.tableData[0].reimUserId,
                    reimVoucherUrl: '',
                    remark: add_data.tableData[0].remark,
                }
                ps.reimVoucherUrl = adupRewardPunish_rawFile_list.value.join(',')
                console.log(adupRewardPunish_rawFile_list.value.join(','), ' adupRewardPunish_rawFile_list.value.join(', ')')
                modifyStaffReimburse(ps).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }
        }
    })


}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除【${table_list.value[0].operName}】报账?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delStaffReim({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    // localStorage.setItem('employee_reimbursement', CircularJSON.stringify(find_data))
    console.log(find_data)
    list_api()
}
//#endregion

//#region 审核
const checkBzRecord = (e) => {
    let rows = table_list.value
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    let fg = true;
    if (fg) {
        let isObj = rows.find(it => it.isCheck != 'NO_CHECK');
        if (isObj) {
            fg = false
            return ElMessage({
                message: `所选报账存在【已审核】记录，不能操作`,
                type: 'warning',
            })
        }
    }



    if (e == 'CHECKED') {
        ElMessageBox.confirm(
            '是否将选中报账<b style="color:red;font-weight:700">通过审核</b>？',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: 'true',
                dangerouslyUseHTMLString: true,
            }
        )
            .then(() => {



                let idArr = rows.map(item => item.id);
                checkStaffReimburse({
                    ids: idArr,
                    isCheck: 'CHECKED',
                    remark: '通过'
                }).then(res => {
                    if (res.code == 1) {
                        list_api()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            })
            .catch((e) => {
                if (e == 'cancel') {
                    ElMessage({
                        type: 'warning',
                        message: '取消成功',
                    })
                }

            })
    } else if (e == 'REFUSED') {
        ElMessageBox.prompt(
            '请输入审核<b style="color:red;font-weight:700">不通过原由</b>？',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: 'true',
                dangerouslyUseHTMLString: true,
            }
        )
            .then(({ value }) => {



                let idArr = rows.map(item => item.id);
                checkStaffReimburse({
                    ids: idArr,
                    isCheck: 'REFUSED',
                    remark: value,
                }).then(res => {
                    if (res.code == 1) {
                        list_api()
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            })
            .catch((e) => {
                if (e == 'cancel') {
                    ElMessage({
                        type: 'warning',
                        message: '取消成功',
                    })
                }

            })
    }
}
//#endregion

//#region 驳回
const setTurnDownStaffReimMd_data = reactive({
    ids: '',
    refuseReason: '',
})
const setTurnDownStaffReimMd_ref = ref('')
const setTurnDownStaffReimMd_off = ref(false)
const setTurnDownStaffReimMd = () => {
    let rows = table_list.value
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    let isCheck = rows.every(it => it.isCheck === 'CHECKED');
    if (!isCheck) {
        return ElMessage({
            message: "只有【已审核】的才能进行驳回操作",
            type: 'warning',
        })
    }
    setTurnDownStaffReimMd_data.ids = ''
    setTurnDownStaffReimMd_data.refuseReason = ''
    setTurnDownStaffReimMd_off.value = true
}
const setTurnDownStaffReimMd_ok_btn = () => {
    console.log(setTurnDownStaffReimMd_data.refuseReason)
    let rows = table_list.value
    let idArr = rows.map(item => item.id);
    setTurnDownStaffReimMd_ref.value.validate((valid, fields) => {
        if (valid) {
            let ps = {
                ids: idArr,
                refuseReason: setTurnDownStaffReimMd_data.refuseReason
            }
            checkRefuse(ps).then(res => {
                if (res.code == 1) {
                    list_api()
                    setTurnDownStaffReimMd_off.value = false
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        }
    })
}
//#endregion

//#region 核销
const Write_off = ref(false)
const Write_data = reactive({
    btlIds: '',
    enterTime: "",
    ids: "",
}) // 入账月份
const Write_data__find_list = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },//
    timeType: '0', //
    stime: '', //
    etime: '', //
    isCheck: 'NO_CHECK',
    moneyTypeIds: '', //
    remark: '', //
    tradeMoney: '', //
    tradeStatus: '1', //
    transName: '', //

})
const Write_timeTypeTime = ref('')
const Write_timeTypeTime_btn = (e) => {
    if (e) {
        Write_timeTypeTime.value = e
        Write_data__find_list.stime = Write_timeTypeTime.value[0]
        Write_data__find_list.etime = Write_timeTypeTime.value[1]
    } else {
        Write_timeTypeTime.value = ''
        Write_data__find_list.stime = ''
        Write_data__find_list.etime = ''
    }
}
const Write_find_btn = () => {
    Write_list_api()
}
const Write_data__list = ref([])
const Write_data__find_list_total = ref(0)
const Write_list_api = () => {
    Write_data__find_list.moneyTypeIds ? Write_data__find_list.moneyTypeIds = [Write_data__find_list.moneyTypeIds] : Write_data__find_list.moneyTypeIds = []
    findBankTradeList(Write_data__find_list).then(res => {
        Write_data__list.value = res.data.list.list
        Write_data__find_list_total.value = res.data.list.total
        Write_data__find_list.moneyTypeIds[0] ? Write_data__find_list.moneyTypeIds = Write_data__find_list.moneyTypeIds[0] : Write_data__find_list.moneyTypeIds = ''
    })
}
// 分页器一夜显示多少数据页面
const Write_size_change_btn = () => {
    Write_data__find_list.page.pageNum = 1
    Write_list_api()
}

// 分页器跳转页面
const Write_current_change_btn = () => {
    Write_list_api()
}

//#region 表格选择
const table_list2 = ref([])
const selection_change_btn2 = (e) => {
    table_list2.value = e
    console.log(e, 'table_list2')
}
//#endregion
const Write_totalshou = ref(0) //累计收
const Write_totalPay = ref(0) //累计支出
const Write_totalcha = ref(0) //累计差

const Write_seledPay = computed(() => {
    let money = 0
    let rows = table_list2.value
    rows.forEach(it => {
        money += parseFloat(it.tradeOutMoney ? it.tradeOutMoney : 0);
    });

    return (money).toFixed(2);

})

const Write_seledGath = computed(() => {
    let money = 0
    let rows = table_list2.value
    rows.forEach(it => {
        money += parseFloat(it.tradeInMoney ? it.tradeInMoney : 0);
    });

    return (money).toFixed(2);

})

const Write_seledBalance = computed(() => {
    let money = 0
    let rows = table_list2.value
    rows.forEach(it => {
        money += Math.abs(parseFloat(it.tradeInMoney ? it.tradeInMoney : 0) - parseFloat(it.tradeOutMoney ? it.tradeOutMoney : 0));
    });
    return (money).toFixed(2);

})
const Write_off_btn = () => {
    let rows = table_list.value
    if (table_list.value.length < 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    } else {
        let isObj = rows.find(it => it.isCheck !== 'CHECKED');
        if (isObj) {
            return ElMessage({
                message: `所选数据存在不是【已审核】，不能核销`,
                type: 'warning',
            })
        } else {
            let retArr = rows.map(item => item.reimUserId);
            // 是否存在不同收款人

            let isEqualUser = [...new Set(retArr)];
            console.log(retArr, isEqualUser)

            if (isEqualUser && isEqualUser.length > 1) {
                return ElMessage({
                    message: "核销收款人必须是【同一用户】",
                    type: 'warning',
                })
            } else {

                let totalGath = 0, totalPay = 0, totalBalance = 0;
                rows.forEach(it => {
                    // // 累计收入
                    totalGath += parseFloat(it.gathMoney);
                    // 累计支出
                    totalPay += parseFloat(it.reimMoney);
                    // // 收支差额
                    totalBalance += Math.abs(parseFloat(it.gathMoney) - parseFloat(it.reimMoney));
                    Write_totalshou.value = (totalGath).toFixed(2);
                    Write_totalPay.value = (totalPay).toFixed(2);
                    Write_totalcha.value = (totalBalance).toFixed(2);
                });
                Write_list_api()
                Write_data.enterTime = ''

                if (table_list.value[0].gathMoney > 0) {
                    Write_data__find_list.tradeStatus = '0'
                } else {
                    Write_data__find_list.tradeStatus = '1'
                }


                Write_off.value = true
            }
        }

    }




}
const Write_ok_btn = () => {

    let rows = table_list2.value

    if (rows.length === 0) {
        return ElMessage({
            message: "请选择要核销的记录",
            type: 'warning',
        })

    } else {
        if (!Write_data.enterTime) {

            return ElMessage({
                message: '请选择入账月份',
                type: 'warning',
            })
        } else if (!table_list.value[0] || table_list.value.length == 0) {
            return ElMessage({
                message: '您未选择报账记录，请关闭弹框重新选择报账记录',
                type: 'warning',
            })

        } else if (table_list.value.length > 1 && rows.length > 1) {
            return ElMessage({
                message: '您有多条报账记录，只能选择1条核销记录',
                type: 'warning',
            })

        } else {
            let ps = {
                btlIds: rows.map(it => it.id),
                enterTime: Write_data.enterTime + ' ' + '00:00:00',
                ids: table_list.value.map(it => it.id),
            }
            cancellationStaffReim(ps).then(res => {
                if (res.code == 1) {
                    list_api()
                    Write_list_api()
                    Write_off.value = false
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        }
    }
    console.log(Write_data)
}
//#endregion

//#region 撤销核销
const cancelWriteOff = () => {
    let rows = table_list.value

    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请至少选择一条要撤销的数据',
            type: 'warning',
        })
    } else {
        let isObj = rows.find(it => it.isCheck != 'CANCELLATION');
        if (isObj) {
            return ElMessage({
                message: '所选数据不是【已报销】，不能撤销',
                type: 'warning',
            })

        } else {
            ElMessageBox.confirm(
                `确定撤销【已报销】的报账记录？`,
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                    distinguishCancelAndClose: 'true',
                }
            )
                .then(() => {
                    cancelStaffReim({
                        ids: [table_list.value[0].id]
                    }).then(res => {
                        if (res.code == 1) {
                            list_api()
                            return ElMessage({
                                message: res.msg,
                                type: 'success',
                            })
                        } else {
                            return ElMessage({
                                message: res.msg,
                                type: 'warning',
                            })
                        }
                    })
                })
                .catch((e) => {
                    if (e == 'cancel') {
                        ElMessage({
                            type: 'warning',
                            message: '取消删除成功',
                        })
                    }

                })



        }
    }
}
//#endregion

//#region 交易记录列表导出
const ex_getWalletListForBack_btn = () => {
    staffReimExport(find_data).then(res => {
        if (res.code == 1) {
            const data = [
                ['经办人信息', '收款人信息', '车公司信息', '车牌号', '业务部门', '报账详情', '支出金额', '支出金额详情', '记账审核状态', '驳回原因', '报账类型', '支付日期', '费用产生日期', '费用结束日期', '入账月份', '添加时间', '操作标识'],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {

                    operUser: res.data[i].operUser,
                    reimUser: res.data[i].reimUser,
                    carOrderReim: res.data[i].carOrderReim,
                    plateNum: res.data[i].plateNum,
                    deptName: res.data[i].deptName,
                    remark: res.data[i].remark,
                    reimMoney: res.data[i].reimMoney,
                    reimMoneyDetail: res.data[i].reimMoneyDetail,
                    isCheck: res.data[i].isCheck == 'CHECKED' ? '已审核' : res.data[i].isCheck == 'CANCELLATION' ? '已报销' : '未通过',
                    refuseReason: res.data[i].refuseReason,
                    moneyTypeName: res.data[i].moneyTypeName,
                    payTime: res.data[i].payTime,
                    costStartTime: res.data[i].costStartTime,
                    costEndTime: res.data[i].costEndTime,
                    enterTime: res.data[i].enterTime,
                    addTime: res.data[i].addTime,
                    operMark: res.data[i].operMark,

                }
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '单位管理后台系统-办公室报账列表.xlsx');
            list_api()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

</script>

<style scoped lang='scss'>
.route-tips {
    max-width: 500px !important;
}

.filter-container {
    line-height: 30px;
    position: relative;
}

.dgts-row {
    display: flex;
    line-height: 20px;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-right: 30px !important;

    /* 列表顶部工具栏统计等文本--begin */
    .dgts-text {
        // 当文本和按钮等放一行时需要加此类样式
        line-height: 30px;
    }

    .tr-it-title {
        font-size: 15px;
    }

    .tr-it {
        font-size: 13px;
    }

    .dgts-text-tj1 {
        line-height: 30px;
        margin: 0px 10px;
        background: #fde2e2;
        border-radius: 5px;
        padding: 0px 10px;
    }

    .dgts-text-tj2 {
        line-height: 30px;
        margin: 0px 10px;
        background: #b3d8ff;
        border-radius: 5px;
        padding: 0px 10px;
    }


}

.c-green {
    color: #008000;
}

.c-yellow {
    color: #FF872A;
}

.c-red {
    color: #FF0000;
}
</style>

<style>
.avatar-uploader .avatar {
    width: 100px;
    height: 50px;
    display: block;
}


.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 50px;
    text-align: center;
}

.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.card_css>.el-card__header {
    padding: 5px !important;
}

.el-table .el-table__cell {
    padding: 0px !important;
}

/* table顶部顶部工具栏 */
.filter-container .dgts-row .el-form-item,
.filter-container .el-form .el-form-item {
    margin-bottom: 0px !important;
}

.filter-container .el-form--inline .el-form-item {
    display: inline-flex;
    vertical-align: middle;
    margin-right: 9px;
}
</style>
